import java.util.StringTokenizer;
import java.util.Stack ;

public class Calculator
{
    /* constant for addition symbol */
    private final char ADD = '+';
    /* constant for subtraction symbol */
    private final char SUBTRACT = '-';
    /* constant for multiplication symbol */
    private final char MULTIPLY = '*';
    /* constant for division symbol */
    private final char DIVIDE = '÷';
    /* the stack */
    private Stack<String> stack;
    private RationalNumber r, r1, r2;

    public Calculator() {
        stack = new Stack<String>();
    }

    public String evaluate (String expr)
    {
        String op1, op2, result = null;
        String token;
        StringTokenizer tokenizer = new StringTokenizer (expr);
        while (tokenizer.hasMoreTokens())
        {
            token = tokenizer.nextToken();

            //如果是运算符，调用isOperator
            if (isOperator(token))
            {
                //从栈中弹出操作数2,将其转化为RationalNumber类型
                op2 = stack.pop();
                r2 = tranIntoRationalNum(op2);
                //从栈中弹出操作数1,将其转化为RationalNumber类型
                op1 = stack.pop();
                r1 = tranIntoRationalNum(op1);
                //根据运算符和两个操作数调用evalSingleOp计算result;
                result = evalSingleOp(token.toCharArray()[0], r1, r2);
                //计算result入栈;
                result = stack.push(result);
            }
            else //如果是操作数
                stack.push(token);
            //操作数入栈;
        }
        return result;
    }

    public  boolean isOperator (String token)
    {
        return ( token.equals("+") || token.equals("-") ||
                token.equals("*") || token.equals("÷") );
    }

    private String evalSingleOp (char operation, RationalNumber op1, RationalNumber op2)
    {
        RationalNumber result = new RationalNumber(0,1);

        switch (operation)
        {
            case ADD:
                result = r1.add(r2);
                break;
            case SUBTRACT:
                result = r1.subtract(r2);
                break;
            case MULTIPLY:
                result = r1.multiply(r2);
                break;
            case DIVIDE:
                result = r1.divide(r2);
        }

        return result.toString();
    }

    public RationalNumber tranIntoRationalNum (String s){
        String token1, token2;

        StringTokenizer tokenizer1 = new StringTokenizer(s, "/");//把操作数以"/"为标记分割开来
        token1 = tokenizer1.nextToken();
        if (tokenizer1.hasMoreTokens()) {//如果有第二个元素就把token1放在分子的位置，token2放在分母的位置
            token2 = tokenizer1.nextToken();
            r = new RationalNumber(Integer.parseInt(token1), Integer.parseInt(token2));
        }
        else {//如果没有第二个元素就把token1放在分子的位置，分母固定为1
            r = new RationalNumber(Integer.parseInt(token1),1);
        }
        return r;
    }
}